#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import json
import os
import time
import requests
import Lib.Logger.log4py as logging
from mj_parser import common_errors

def login_on_error(func):
    def func_wrapper(self, *args, **kwargs):
        for retries in range(0, 3):
            res = func(self, *args, **kwargs)
            if res is not None:
                return res
            self.login()

    return func_wrapper


def log_error_on_none(func):
    def func_wrapper(self, *args, **kwargs):
        res = func(self, *args, **kwargs)
        if res is None:
            self.logger.error('log_error_on_none')




class LandRoverWebSource:
    URL = 'https://epc.jlr-apps.com/api/vin/decode/11/{0}?languageId=1&searchType=VIN&t={1}'
    LOGIN_URL = 'https://epc.jlr-apps.com/login'
    HEADERS = {
        'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36",
        'Key': 'f3a9b43d-77d6-4f9e-b07b-0039a41712ca',
        'ClientSign': '6c2912669b37591b0e96f2bf08977efd',
    }


    PROXIES = {
        'http': 'http://101.132.46.34:5870',
        'https': 'http://101.132.46.34:5870'
    }

    def __init__(self, root_path='.'):
        self.logger = logging.get_logger('crawler', 'LandroverWebSource')
        self.root_path = root_path
        self.conf_path = os.path.join(root_path, 'conf')
        self.cookie_file = os.path.join(self.conf_path, 'landrover_cookie.txt')
        self.data_path = os.path.join(root_path, "data")
        self.session = requests.Session()

    def request_get(self, url, decode_json=True):
        ret = self.session.get(url, headers=LandRoverWebSource.HEADERS, proxies=LandRoverWebSource.PROXIES, verify=False)

        if ret.status_code != 200:
            self.logger.error(url)
            self.logger.error(ret.text)
            return None

        if decode_json:
            return ret.json()

        return ret.text


    def request_post(self, url, content_type, payload, decode_json=True):
        headers = dict(LandRoverWebSource.HEADERS)
        headers['Content-Type'] = content_type
        if type(payload) != str:
            payload = json.dumps(payload, ensure_ascii=False)
        ret = self.session.post(url, data=payload, headers=headers, proxies=LandRoverWebSource.PROXIES, verify=False)
        if ret.status_code != 200:
            self.logger.error(url)
            self.logger.error(payload)
            self.logger.error(ret.text)
            return None

        if decode_json:
            return ret.json()

        return ret.text

    def search_vin(self, str_vin):
        cur_url = self.URL.format(str_vin, int(round(time.time() * 1000)))
        content = self.request_get(cur_url, decode_json=False)
        if content is not None:
            vin_file = os.path.join(self.data_path, '{0}.json'.format(str_vin))
            with open(vin_file, 'wb') as fo:
                fo.write(content.encode('utf-8'))
            return vin_file
        return None

    def get_data(self, str_vin, brand, group):
        # 实例
        # driver.get("https://epc.jlr-apps.com/api/vin/decode/11/SALVA2BG2DH800209?languageId=1&searchType=VIN&t=1513847130415")
        vin_file = self.search_vin(str_vin)
        if vin_file is None:
            return common_errors.ERR_TCP_ERROR, None
        return common_errors.ERR_SUCCESS, vin_file


if __name__ == '__main__':
    lr = LandRoverWebSource()
    # 无效vin
    lr.get_data('SAL1A2BG2DH800200', '', '')
    # 有效vin
    lr.get_data('SALVA2BG2DH800209', '', '')